package com.example.project.config.shiro;

import com.example.project.entity.TAdmin;
import com.example.project.service.TAdminService;
import com.example.project.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    @Autowired
    TAdminService tAdminService;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroCacheObj shiroCacheObj = (ShiroCacheObj) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();


        TAdmin tAdmin = tAdminService.queryById(shiroCacheObj.getUserId());

        //设置角色
        Set<String> roles = new HashSet<>();

        //从数据库中获取该用户的角色和权限
//        roles.add(tUser.getUserType());
//
//        authorizationInfo.addRoles(roles);

//        List<Map> result=troleService.getRoleModulebyUserId(cacheObj.getUserId());
//
//        Set<String> moduleSet = new HashSet<>();
//
//        for (Map map:result){
//            moduleSet.add((String) map.get("rolemodule"));
//        }
//
//        info.setStringPermissions(moduleSet);
        return info;
    }

    /**
     * private UserService userService;
     * <p>
     * 获取即将需要认证的信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("-------身份认证方法--------");
        String userName = (String) authenticationToken.getPrincipal();
        String userPwd = new String((char[]) authenticationToken.getCredentials());

        //        TUser userInfo=tuserService.queryById(userId);
        TAdmin userInfo= tAdminService.queryOne(new TAdmin(){{setUserName(userName);}});



        if(userInfo==null){

            logger.error("未获取到用户信息");
            throw new AccountException("用户名不正确");
//            userPwd.equals(userInfo.getUserPwd())

        }else{
            boolean one=false;
            if(false){
                //游客不需要密码
                one=true;
            }else{
                String sqlPwd=userInfo.getUserPwd();
                String getPwd= MD5Utils.md5(userPwd);

                one=sqlPwd.equals(getPwd);

                logger.debug("密码校验：：：{}，结果：：：{}",sqlPwd+"=="+getPwd,userPwd.equals(getPwd));
            }
            if (!one) {
                throw new IncorrectCredentialsException();
            } else {
//            String key= UUIDUtils.getUUID();
                ShiroCacheObj shiroCacheObj =new ShiroCacheObj();
                shiroCacheObj.setUserId(userInfo.getPkid());
                shiroCacheObj.setUserName(userInfo.getUserName());
                shiroCacheObj.setUserNick(userInfo.getUserNick());

                //5. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
                return new SimpleAuthenticationInfo(shiroCacheObj, userPwd, userInfo.getUserName());
            }
        }



    }
}